import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_project/add_publish/pic_video_common_utils.dart';
import '../common/privacy/dialog_common_view.dart';
import '../common/route_page/route_name.dart';
import '../common/utils/image_picker_utils.dart';
import '../common/utils/screen_size_utils.dart';
import '../config/loading_toast.dart';
import '../config/theme_color.dart';
import '../generated/l10n.dart';
import '../home/home_video_details_model.dart';
import '../home/home_video_details_page.dart';
import '../requst/dio_http_utils.dart';
import '../video/video_player_view.dart';

class VideoPicContentView extends StatefulWidget {
  final VideoDetailsRespModel? itemDetailModel;
  final bool isFromDetails;

  const VideoPicContentView(
      {this.itemDetailModel, this.isFromDetails = false, super.key});

  @override
  State<VideoPicContentView> createState() => _VideoPicContentViewState();
}

class _VideoPicContentViewState extends State<VideoPicContentView> {
  final TextEditingController promptController = TextEditingController();
  final TextEditingController negPromptController = TextEditingController();
  FocusNode promptNode = FocusNode();
  FocusNode negPromptNode = FocusNode();
  final ValueNotifier<int> randomNum = ValueNotifier<int>(0);
  final ValueNotifier<String> rateStr = ValueNotifier<String>('16:9');
  Map rateMap = PicVideoCommonUtils.rateMap();
  List rateKeyList = [];
  List rateValueList = [];
  String textUmodelStr = '';
  String imgUmodelStr = '';
  String videoUmodelStr = '';
  MethodChannel methodChannel = const MethodChannel('initTOSSDK');
  String filePath = '';
  int imgId = 0;
  final ValueNotifier<String> showFileUrl = ValueNotifier<String>('');

  @override
  Widget build(BuildContext context) {
    double imgWidth = ScreenSizeUtils.deviceScreenWidth(context) - 30;
    double imgHeight = PicVideoCommonUtils.imgHeight;
    return ListView(
      children: [
        const SizedBox(
          height: 10,
        ),
        GestureDetector(
          onTap: () {
            ImagePickerUtils.selectPhotoAndVideoFromSheet(context,
                callBackUrl: (res) {
              if (res != null) {
                filePath = res ?? '';
                PicVideoCommonUtils.requestOTSToken(filePath,
                    methodChannel: methodChannel);
              }
            });
          },
          child: ValueListenableBuilder(
              valueListenable: showFileUrl,
              builder: (BuildContext context, String value, Widget? child) {
                return value.isNotEmpty
                    ? PicVideoCommonUtils.isPictrueConetent(value)
                        ? Image.network(
                            value,
                            fit: BoxFit.cover,
                            width: imgWidth,
                            height: imgHeight,
                          )
                        : VideoPlayerView(
                            path: value,
                          )
                    : Container(
                        color: ThemeColor.mainBgColor,
                        width: imgWidth,
                        height: imgHeight,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.camera_alt_outlined,
                              color: ThemeColor.textColorSecond,
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            Text(
                              '可上传图片or视频，如不需要，直接输入提示词',
                              style:
                                  TextStyle(color: ThemeColor.hint777777Color),
                            ),
                          ],
                        ),
                      );
              }),
        ),
        PicVideoCommonUtils.getItemView(
            leftName: S.of(context).prompt,
            focusNode: promptNode,
            textEditingController: promptController,
            placeStr: '输入提示词'),
        PicVideoCommonUtils.getItemView(
            leftName: S.of(context).negativePrompt,
            focusNode: negPromptNode,
            textEditingController: negPromptController,
            placeStr: '输入负向提示词'),
        ValueListenableBuilder(
            valueListenable: randomNum,
            builder: (BuildContext context, int value, Widget? child) {
              return PicVideoCommonUtils.getChoseItemView(
                  leftName: S.of(context).seed,
                  rightName: value.toString(),
                  refreshAction: () {
                    getRandomNum();
                  });
            }),
        widget.isFromDetails
            ? SizedBox(
                height: PicVideoCommonUtils.itemHeight,
              )
            : ValueListenableBuilder(
                valueListenable: rateStr,
                builder: (BuildContext context, String value, Widget? child) {
                  return PicVideoCommonUtils.getChoseItemView(
                      leftName: S.of(context).aspectRatio,
                      rightName: value,
                      isHiddenRefresh: true,
                      tapAction: () {
                        cancelKeyBoardResign();
                        PicVideoCommonUtils.getRateBottomView(context,
                            rateKeyList: rateKeyList, tapAction: (res) {
                          rateStr.value = res;
                        });
                      });
                }),
        Container(
          color: Colors.white,
          height: PicVideoCommonUtils.middleHeight(context),
        ),
        PicVideoCommonUtils.deleteViewAndSubmitAction(context, delAction: () {
          cancelKeyBoardResign();
          if (showFileUrl.value.isNotEmpty) {
            showFileUrl.value = '';
          } else {
            toast('暂无可删除对图片或者视频');
          }
        }, submitAction: () {
          submitToGenerateAction();
        }),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    initChannelGetResultFromOriginal();
    rateKeyList = rateMap.keys.toList();
    rateValueList = rateMap.values.toList();
    if (widget.itemDetailModel != null) {
      VideoDetailsRespModel detailsRespModel =
          widget.itemDetailModel ?? VideoDetailsRespModel();
      promptController.text = detailsRespModel.prompt ?? '';
      negPromptController.text = detailsRespModel.negativePrompt ?? '';
      randomNum.value = detailsRespModel.seed ?? 0;
      rateStr.value = detailsRespModel.rateStr;
      if (detailsRespModel.videoOriginalUrl.isNotEmpty) {
        showFileUrl.value = detailsRespModel.videoOriginalUrl;
        videoUmodelStr = detailsRespModel.umModel;
        imgId = int.parse(detailsRespModel.fileId);
      } else if (detailsRespModel.imgOriginalUrl.isNotEmpty) {
        showFileUrl.value = detailsRespModel.imgOriginalUrl;
        imgUmodelStr = detailsRespModel.umModel;
        imgId = int.parse(detailsRespModel.fileId);
      } else {
        textUmodelStr = detailsRespModel.umModel;
      }
      setState(() {});
    } else {
      getRandomNum();
      getUnderlyingModels(1);
      getUnderlyingModels(2);
      getUnderlyingModels(3);
    }
  }

  getRandomNum() {
    randomNum.value = PicVideoCommonUtils.getRandomNum();
  }

  getUnderlyingModels(int type) async {
    var res = await HttpDioUtils.request('model/getAllVideoUnderlyingModels',
        params: {'UmodelType': type});
    if (res != null && res['ErrCode'] == 0) {
      List modelList = res['Resp']['Models'];
      if (modelList.isNotEmpty) {
        if (type == 1) {
          textUmodelStr = modelList.first;
        } else if (type == 2) {
          imgUmodelStr = modelList.first;
        } else if (type == 3) {
          videoUmodelStr = modelList.first;
        }
      }
    }
  }

  //取消键盘响应
  void cancelKeyBoardResign() {
    if (promptNode.hasFocus) {
      promptNode.unfocus();
    }
    if (negPromptNode.hasFocus) {
      negPromptNode.unfocus();
    }
  }

  //生成图片
  submitToGenerateAction() async {
    String promptStr = promptController.text;
    String negativePromptStr = negPromptController.text;
    if (promptStr.isEmpty) {
      toast('请输入提示词');
      return;
    }
    cancelKeyBoardResign();
    String widthHeightStr = rateMap[rateStr.value];
    List widthHeightList = widthHeightStr.split('x');
    int width = int.parse(widthHeightList.first);
    int height = int.parse(widthHeightList.last);
    String fileUrl = showFileUrl.value;
    Map<String, dynamic> dataMap = {
      'GptPromptist': 0,
      'ToPromptist': 0,
      'Height': height,
      'VideoUpload': [],
      'NegativePrompt': negativePromptStr,
      'Prompt': promptStr,
      'OriginalUmodel': getRightUmodelStr(fileUrl),
      'Seed': randomNum.value,
      'Width': width,
      "AspectRatio": rateStr.value,
    };
    if (fileUrl.isNotEmpty) {
      if (PicVideoCommonUtils.isPictrueConetent(fileUrl)) {
        dataMap['ImgUrl'] = fileUrl;
        dataMap['Img'] = imgId;
      } else {
        dataMap['VideoUrl'] = fileUrl;
        dataMap['Video'] = imgId;
      }
    }
    debugPrint('请求信息${dataMap.toString()}');
    String apiUrl = 'createVideoGenerateTask';
    if (PicVideoCommonUtils.isPictrueConetent(fileUrl)) {
      apiUrl = 'createImg2VideoGenerateTask';
    } else {
      apiUrl = 'createVideo2VideoGenerateTask';
    }
    debugPrint('请求url:$apiUrl');
    var res = await HttpDioUtils.request('task/$apiUrl', params: dataMap);
    if (res != null && res['ErrCode'] == 0) {
      int videoId = res['Resp']['VideoId'];
      saveSuccess(1, videoId);
    }
  }

  saveSuccess(int type, int fileId) {
    // CommonStringConfig.likeEventBus.fire({"isRefreshHomePage": true});
    ConfirmAlertDialog.showView(context,
        title: '',
        content: '需要等待1～10分钟，结果会在【我的】进行查看，同时可以生成四个作品', rightAction: () {
      RouteNames.pushReplacement(HomeVideoDetailsPage(
        isFromDetails: widget.isFromDetails,
        id: fileId,
        type: type,
      ));
    });
  }

  //根据类型传给后台对应的模型
  String getRightUmodelStr(String fileUrl) {
    if (fileUrl.isNotEmpty) {
      if (!PicVideoCommonUtils.isPictrueConetent(fileUrl)) {
        return videoUmodelStr;
      }

      if (PicVideoCommonUtils.isPictrueConetent(fileUrl)) {
        return imgUmodelStr;
      }
    }

    return textUmodelStr;
  }

  //从原生拿到ots上传结果
  initChannelGetResultFromOriginal() {
    const MethodChannel('uploadMedia').setMethodCallHandler((call) async {
      if (call.method == 'upload_media_file') {
        // 处理接收到的消息
        dynamic arguments = call.arguments;
        if (arguments != null) {
          List<String> fileList = filePath.split('/');
          String fileName = fileList.last;
          String pathStr =
              PicVideoCommonUtils.isPictrueConetent(fileName) ? 'png' : 'mp4';
          String path = "platform/$pathStr/upload/$fileName";
          Map<String, dynamic> dataMap = {
            "Category": 0,
            "IsShow": true,
            "Path": path,
            "filePath": path,
            "name": fileName,
            "type": 1 //0代表图片  1代表视频,
          };
          try {
            var res = await HttpDioUtils.request('media/uploadMedia',
                params: dataMap);
            if (res != null && res['ErrCode'] == 0) {
              showFileUrl.value = res['Resp']['Video']['Url'];
              imgId = res['Resp']['Video']['Id'];
              debugPrint('上传给后台的数据$showFileUrl$imgId');
            } else {}
          } catch (e) {
            debugPrint(e.toString());
          }
        }
      }
    });
  }
}
